<template>
    <div class="email-container">
      <div class="email-header">
        <h1>{{ emailTitle }}</h1>
        <button @click="goBack" class="back-button">返回</button>
      </div>
      
      <!-- 搜索功能区域 -->
      <div class="user-search">
        <div class="search-box">
          <input 
            type="text" 
            v-model="searchContent" 
            placeholder="请输入搜索内容"
            @input="filterNumberInput"
          >
        </div>
        <div class="search-type">
          <select v-model="searchType">
            <option value="id">根据ID搜索</option>
            <option value="username">根据用户名搜索</option>
          </select>
        </div>
        <button @click="searchUsers" class="search-button">搜索</button>
      </div>
  
      <!-- 显示搜索结果 -->
      <div v-if="searchResults && searchResults.length > 0" class="search-results">
        <h3>搜索结果：</h3>
        <div class="result-item" v-for="(user, index) in searchResults" :key="index">
          <p><strong>ID：</strong>{{ user.id }}</p>
          <p><strong>用户名：</strong>{{ user.userName }}</p>
          <button @click="addFriend(user.userName)" class="add-friend-button">添加好友</button>
        </div>
      </div>
      <div v-else-if="searchPerformed && searchResults.length === 0" class="search-results">
        <h3>暂无此用户</h3>
      </div>
  
      <!-- 邮件筛选选项 -->
      <div class="mail-filter">
        <button 
          :class="['filter-button', { active: selectedMailType === 0 }]"
          @click="selectMailType(0)"
        >
          未看过的邮件
        </button>
        <button 
          :class="['filter-button', { active: selectedMailType === 1 }]"
          @click="selectMailType(1)"
        >
          已看过的邮件
        </button>
        <button 
          :class="['filter-button', { active: selectedMailType === 10 }]"
          @click="selectMailType(10)"
        >
          我发送的邮件
        </button>
        <button 
          :class="['filter-button', { active: selectedMailType === 11 }]"
          @click="selectMailType(11)"
        >
          我的好友
        </button>
      </div>
      
      <div class="email-content">
        <div v-if="emails && emails.length > 0 && selectedMailType !== 11">
          <div class="email-list">
            <!-- 使用 slice().reverse() 对邮件列表进行逆序 -->
            <div 
              class="email-item" 
              v-for="(email, index) in emails.slice().reverse()" 
              :key="index"
              :class="{ 'read': email.type === 1 }"
            >
              <h3>发送者：{{ email.sendMessage }}</h3>
              <p v-if="selectedMailType === 10" class="email-receiver">接收者：{{ email.receiveMessage }}</p>
              <p class="email-status">状态：{{ email.type === 0 ? '未读' : '已读' }}</p>
              <p class="email-meta">发送时间：{{ formatDate(email.time) }}</p>
              <button @click="viewEmailDetail(email)" class="view-detail-button">查看内容</button>
            </div>
          </div>
        </div>
        <div v-else-if="friends && friends.length > 0 && selectedMailType === 11">
          <div class="friend-list">
            <div class="friend-item" v-for="(friend, index) in friends" :key="index">
              <p><strong>好友用户名：</strong>{{ friend }}</p>
              <button @click="showSendMessageBox(friend)" class="send-message-button">发消息</button>
              <div v-if="selectedFriend === friend" class="send-message-box">
                <textarea
                  v-model="messageContent"
                  placeholder="请输入消息内容"
                ></textarea>
                <button @click="sendMessage">发送</button>
                <button @click="cancelSendMessage">取消</button>
              </div>
            </div>
          </div>
        </div>
        <div v-else>
          <p v-if="selectedMailType !== 11">暂无邮件</p>
          <p v-else>暂无好友</p>
        </div>
      </div>
      
      <!-- 邮件详情模态框 -->
      <div v-if="showEmailDetail" class="modal">
        <div class="modal-content">
          <span class="close" @click="closeModal">&times;</span>
          <h2>邮件详情</h2>
          <div class="email-detail">
            <p><strong>发送者：</strong>{{ selectedEmail.sendMessage }}</p>
            <p v-if="selectedMailType === 10"><strong>接收者：</strong>{{ selectedEmail.receiveMessage }}</p>
            <p><strong>状态：</strong>{{ selectedEmail.type === 0 ? '未读' : '已读' }}</p>
            <div><strong>内容：</strong><pre>{{ selectedEmail.message }}</pre></div>
            <p><strong>发送时间：</strong>{{ formatDate(selectedEmail.time) }}</p>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script lang="ts">
  import { defineComponent } from 'vue';
  import { useRouter } from 'vue-router';
  
  export default defineComponent({
    data() {
      return {
        userInfo: {
          username: ''
        }, // 用户信息
        selectedMailType: 0, // 默认显示未看过的邮件
        emails: [], // 邮件列表
        friends: [], // 好友列表
        showEmailDetail: false, // 是否显示邮件详情模态框
        selectedEmail: null, // 选中的邮件
        searchContent: '', // 搜索工具内容
        searchType: 'id', // 搜索功能区域类型，默认根据ID搜索
        searchResults: [], // 搜索功能结果
        searchPerformed: false, // 是否执行过搜索
        selectedFriend: null, // 选中的好友
        messageContent: '', // 消息内容
      };
    },
    setup() {
      const router = useRouter();
      return { router };
    },
    computed: {
      emailTitle() {
        return `${this.userInfo.username}的个人邮箱`;
      }
    },
    created() {
      this.fetchUserInfo(); // 获取用户信息
      this.fetchMails(this.selectedMailType); // 获取邮件列表
    },
    methods: {
      // 获取用户信息
      fetchUserInfo() {
        const storedUserInfo = localStorage.getItem('userInfo');
        if (storedUserInfo) {
          this.userInfo = JSON.parse(storedUserInfo);
        }
      },
      // 返回按钮点击事件
      goBack() {
        const loginType = localStorage.getItem('loginType') || 'user';
        const route = loginType === 'user' ? '/profile' : '/manager-dashboard';
        this.router.push(route);
      },
      // 获取邮件列表
      async fetchMails(type: number) {
        const token = localStorage.getItem('token');
        if (!token || !this.userInfo.username) {
          return;
        }
  
        try {
          const response = await fetch(`http://localhost:8080/lzl_content2_war_exploded/emailPrint?username=${this.userInfo.username}&type=${type}`, {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
            }
          });
  
          const data = await response.json();
  
          if (response.ok) {
            this.emails = data;
          } else {
            alert('获取邮件失败！');
          }
        } catch (error) {
          console.error('Error fetching emails:', error);
          alert('获取邮件时出错！');
        }
      },
      // 获取好友列表
      async fetchFriends() {
        const token = localStorage.getItem('token');
        if (!token || !this.userInfo.username) {
          return;
        }
  
        try {
          const response = await fetch(`http://localhost:8080/lzl_content2_war_exploded/emailGetFriend?username=${this.userInfo.username}`, {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
            }
          });
  
          if (response.ok) {
            this.friends = await response.json(); // 直接获取好友列表
          } else {
            alert('获取好友列表失败！');
          }
        } catch (error) {
          console.error('Error fetching friends:', error);
          alert('获取好友列表时出错！');
        }
      },
      // 切换邮件类型
      selectMailType(type: number) {
        this.selectedMailType = type;
        if (type === 11) {
          this.fetchFriends(); // 如果是好友列表，则获取好友
        } else {
          this.fetchMails(type); // 否则获取对应类型的邮件
        }
      },
      // 格式化日期
      formatDate(dateString: string) {
        const options: Intl.DateTimeFormatOptions = { 
          year: 'numeric', 
          month: 'numeric', 
          day: 'numeric',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        };
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', options);
      },
      // 查看邮件详情
      async viewEmailDetail(email) {
        // 调用后端接口，将邮件内容和用户名发送给后端
        await this.sendEmailInfoToBackend(email.message, this.userInfo.username);
        
        this.selectedEmail = email;
        this.showEmailDetail = true;
      },
      // 将邮件内容和用户名发送给后端
      async sendEmailInfoToBackend(messageContent: string, username: string) {
        const token = localStorage.getItem('token');
        if (!token) {
          return;
        }
  
        try {
          const response = await fetch('http://localhost:8080/lzl_content2_war_exploded/emailUpdateType', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
              username: username,
              message: messageContent
            })
          });
  
          if (!response.ok) {
            console.error('发送邮件信息到后端失败:', await response.text());
          }
        } catch (error) {
          console.error('Error sending email info to backend:', error);
        }
      },
      // 关闭模态框
      closeModal() {
        this.showEmailDetail = false;
        this.selectedEmail = null;
      },
      // 搜索 |功能实现
      async searchUsers() {
        if (!this.searchContent.trim()) {
          alert('请输入想要搜索的用户');
          return;
        }
  
        if (this.searchType === 'id' && !/^\d+$/.test(this.searchContent)) {
          alert('当根据ID搜索时，只能输入数字');
          return;
        }
  
        this.searchPerformed = true;
  
        const token = localStorage.getItem('token');
        if (!token) {
          return;
        }
  
        try {
          const response = await fetch(`http://localhost:8080/lzl_content2_war_exploded/emailSelectUser?searchType=${this.searchType}&searchContent=${encodeURIComponent(this.searchContent)}`, {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
            }
          });
  
          const data = await response.json();
  
          if (response.ok) {
            this.searchResults = data;
          } else {
            alert('搜索失败！');
          }
        } catch (error) {
          console.error('Error searching users:', error);
          alert('搜索时出错！');
        }
      },
      // 限制输入框只能输入数字
      filterNumberInput() {
        if (this.searchType === 'id') {
          this.searchContent = this.searchContent.replace(/[^\d]/g, '');
        }
      },
      // 添加好友按钮点击事件
      async addFriend(friendUsername) {
        const currentUsername = this.userInfo.username;
  
        if (!currentUsername) {
          alert('未获取到当前用户信息');
          return;
        }
  
        const token = localStorage.getItem('token');
        if (!token) {
          return;
        }
  
        try {
          const response = await fetch('http://localhost:8080/lzl_content2_war_exploded/emailAddUser', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
              currentUsername: currentUsername,
              friendUsername: friendUsername
            })
          });
  
          const data = await response.json();
  
          if (response.ok) {
            alert(`成功添加好友：${friendUsername}`);
          } else {
            alert(`添加好友失败：${data.message || '未知错误'}`);
          }
        } catch (error) {
          console.error('Error adding friend:', error);
          alert('添加好友时出错！');
        }
      },
      // 显示发消息框
      showSendMessageBox(friend) {
        this.selectedFriend = friend;
        this.messageContent = '';
      },
      // 取消发送消息
      cancelSendMessage() {
        this.selectedFriend = null;
        this.messageContent = '';
      },
      // 发送消息
      async sendMessage() {
        if (!this.messageContent.trim()) {
          alert('请输入消息内容');
          return;
        }
  
        const currentUsername = this.userInfo.username;
        const friendUsername = this.selectedFriend;
        const message = this.messageContent;
  
        if (!currentUsername || !friendUsername) {
          alert('发送消息失败：缺少用户信息');
          return;
        }
  
        const token = localStorage.getItem('token');
        if (!token) {
          return;
        }
  
        try {
          const response = await fetch('http://localhost:8080/lzl_content2_war_exploded/emailSend', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
              currentUsername: currentUsername,
              friendUsername: friendUsername,
              message: message
            })
          });
  
          const data = await response.json();
  
          if (response.ok) {
            alert(`成功发送消息给 ${friendUsername}`);
            this.cancelSendMessage();
          } else {
            alert(`发送消息失败：${data.message || '未知错误'}`);
          }
        } catch (error) {
          console.error('Error sending message:', error);
          alert('发送消息时出错！');
        }
      }
    }
  });
  </script>
  
  <style scoped>
  .email-container {
    font-family: Arial, sans-serif;
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .email-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 2px solid #4CAF50;
  }
  
  h1 {
    margin: 0;
    color: #333;
    font-size: 24px;
  }
  
  .back-button {
    background-color: #4CAF50;
    color: white;
    border: none;
    padding: 8px 15px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
  }
  
  .back-button:hover {
    background-color: #45a049;
  }
  
  /* 搜索功能区域样式 */
  .user-search {
    display: flex;
    margin-bottom: 20px;
    gap: 10px;
  }
  
  .search-box {
    flex-grow: 1;
  }
  
  .search-box input {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }
  
  .search-type select {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }
  
  .search-button {
    background-color: #2196F3;
    color: white;
    border: none;
    padding: 8px 15px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
  }
  
  .search-button:hover {
    background-color: #0b7dda;
  }
  
  /* 搜索可结果样式 */
  .search-results {
    background-color: #f9f9f9;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 5px;
    margin-bottom: 20px;
  }
  
  .search-results h3 {
    margin-top: 0;
    color: #333;
  }
  
  .result-item {
    padding: 10px;
    border-bottom: 1px solid #eee;
    position: relative;
  }
  
  .result-item:last-child {
    border-bottom: none;
  }
  
  .add-friend-button {
    position: absolute;
    bottom: 10px;
    right: 10px;
    background-color: #4CAF50;
    color: white;
    border: none;
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
  }
  
  .add-friend-button:hover {
    background-color: #45a049;
  }
  
  /* 邮件筛选选项样式 */
  .mail-filter {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }
  
  .filter-button {
    padding: 8px 15px;
    background-color: #f1f1f1;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
  }
  
  .filter-button.active {
    background-color: #2196F3;
    color: white;
  }
  
  .filter-button:hover:not(.active) {
    background-color: #e0e0e0;
  }
  
  .email-content {
    background-color: #f9f9f9;
    padding: 20px;
    border: 1px solid #eee;
    border-radius: 5px;
  }
  
  .email-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .email-item {
    background-color: white;
    padding: 15px;
    border-radius: 5px;
    border: 1px solid #ddd;
    position: relative;
  }
  
  .email-item.read {
    background-color: #f5f5f5;
  }
  
  .email-item h3 {
    margin-top: 0;
    color: #333;
  }
  
  .email-item p {
    margin: 10px 0;
    color: #666;
  }
  
  .email-meta {
    font-size: 12px;
    color: #888;
    margin-top: 10px;
  }
  
  .email-status {
    font-size: 12px;
    color: #888;
    margin-top: 10px;
  }
  
  .email-receiver {
    font-size: 12px;
    color: #888;
    margin-top: 10px;
  }
  
  .view-detail-button {
    background-color: #2196F3;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
    position: absolute;
    bottom: 15px;
    right: 15px;
  }
  
  .view-detail-button:hover {
    background-color: #0b7dda;
  }
  
  .friend-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .friend-item {
    background-color: white;
    padding: 15px;
    border-radius: 5px;
    border: 1px solid #ddd;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .friend-item p {
    margin: 5px 0;
    color: #333;
  }
  
  .send-message-button {
    background-color: #4CAF50;
    color: white;
    border: none;
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
  }
  
  .send-message-button:hover {
    background-color: #45a049;
  }
  
  .send-message-box {
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .send-message-box textarea {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    resize: vertical;
    min-height: 80px;
  }
  
  .send-message-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  
  .send-button, .cancel-button {
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
  }
  
  .send-button {
    background-color: #2196F3;
    color: white;
    border: none;
  }
  
  .send-button:hover {
    background-color: #0b7dda;
  }
  
  .cancel-button {
    background-color: #f1f1f1;
    color: #333;
    border: none;
  }
  
  .cancel-button:hover {
    background-color: #e0e0e0;
  }
  
  /* 模态框样式 */
  .modal {
    display: block;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.4);
  }
  
  .modal-content {
    background-color: #fefefe;
    margin: 15% auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    max-width: 600px;
    border-radius: 5px;
    position: relative;
  }
  
  .close {
    position: absolute;
    top: 10px;
    right: 20px;
    color: #aaa;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
  }
  
  .close:hover {
    color: black;
  }
  
  .email-detail {
    margin-top: 20px;
  }
  
  .email-detail p {
    margin: 10px 0;
    line-height: 1.6;
  }
  
  .email-detail pre {
    white-space: pre-wrap;
    background-color: #f9f9f9;
    padding: 10px;
    border-radius: 4px;
  }
  </style>